package com.bjpower.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.bjpower.entity.UserPayConfig;
import com.bjpower.entity.UserPayInfo;
import com.bjpower.mapper.UserPayConfigMapper;
import com.bjpower.mapper.UserPayInfoMapper;
import com.bjpower.models.dto.PayConfigDto;
import com.bjpower.models.request.PayWayInfoRequest;
import com.bjpower.service.GetPayWayService;
import com.bjpower.utils.CheckSign;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

@Service
public class GetPayWayServiceImpl implements GetPayWayService {

    @Resource
    private UserPayConfigMapper userPayConfigMapper;

    @Resource
    private UserPayInfoMapper userPayInfoMapper;
    @Override
    public PayConfigDto getPayWay(PayWayInfoRequest payWayInfoRequest, HttpServletRequest request) {
        //根据用户商品信息查询数据库信息
        QueryWrapper<UserPayConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("user_no",payWayInfoRequest.getUserNo())
                .eq("product_code",payWayInfoRequest.getPayProductCode());
        UserPayConfig userPayConfig = userPayConfigMapper.selectOne(wrapper);
        if (userPayConfig == null){
            throw new RuntimeException("用户名或者商品编码错误");
        }

        //验证签名是否正确,获取数据库中的信息经过加密算法计算
        Boolean sign = CheckSign.checkSign(payWayInfoRequest, userPayConfig.getAppSecret(), userPayConfig.getAppKey());
        if (!sign){
            throw new RuntimeException("签名错误");
        }
       // 判断支付参数是否有信息
        QueryWrapper<UserPayInfo> infoWrapper = new QueryWrapper<>();
        infoWrapper.eq("user_no",payWayInfoRequest.getUserNo())
                .eq("product_code",payWayInfoRequest.getPayProductCode())
                .eq("way_code",payWayInfoRequest.getWayCode());
        UserPayInfo userPayInfo = userPayInfoMapper.selectOne(infoWrapper);
        if (userPayInfo == null){
            throw new RuntimeException("支付参数错误");
        }
        //返回商户信息
        PayConfigDto configDto = new PayConfigDto();
        configDto.setClientIp(request.getRemoteAddr());
        configDto.setTerminalIp(userPayConfig.getMerchantServerIp().split(",")[0]);
        configDto.setTdpformName(userPayConfig.getShopName());
        configDto.setGatewayBgUrl("http://localhost:8002/gateway/notice");
        configDto.setGatewayOrderId(String.valueOf(IdWorker.getId()));
        configDto.setPayConfig(userPayInfo.getPayConfig());

        return configDto;
    }
}
